<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="content-type" content="text/html" charset="utf-8"/>
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"/>
    <meta http-equiv="X-UA-Compatible" content="ie=edge"/>
    <title>Title</title>
    <link rel="stylesheet" href="lib/font-awesome/css/font-awesome.css">
    <link rel="stylesheet" href="css/jquery-search-input.css">
    <style>
        #canvas{
            box-shadow: 0 0 10px 2px #f1f1f1;
        }
    </style>
</head>
<body>
<div>
    <canvas id="canvas"></canvas>
</div>

<script src="lib/jquery-3.5.1.js"></script>
<script src="js/jquery-search-input.js"></script>
<script>
    const imageUrl = 'https://file.sxkid.com/images/mkt/bf8c4d16435d4ea6aa1f1f2801d7327a.png';
    const $canvas = $('#canvas');
    const canvas = $canvas.get(0);
    canvas.width = 600;
    canvas.height = 600;
    const ctx = canvas.getContext('2d');

    draw().then(function () {
        console.log('ok')
    });

    function toBase64(){
        const b64 = canvas.toDataURL('image/jpeg', .9);
    }

    var balls = [];
    $canvas.click(function(){
        //标准的获取鼠标点击相对于canvas画布的坐标公式
        var x = event.pageX - canvas.getBoundingClientRect().left;
        var y = event.pageY - canvas.getBoundingClientRect().top;
        for(var i = 0; i < balls.length; i++){
            ctx.beginPath();
            ctx.arc(balls[i].X, balls[i].Y, balls[i].R, 0, Math.PI*2);
            if(ctx.isPointInPath(x, y)){
                ctx.fillStyle = "red";
                ctx.fill();
            }
        }
    });

    async function draw() {
        const image = await loadImage(imageUrl);
        const imageRatio = image.naturalWidth / image.naturalHeight;

        //定宽
        const imageWidth = canvas.width;
        //等比缩放高
        const imageHeight = imageWidth / imageRatio;

        let x= 0, y = (canvas.height - imageHeight) / 2;
        ctx.drawImage(image, x, y, imageWidth, imageHeight)
    }

    function loadImage(src) {
        return new Promise((resolve, reject) => {
            let image = new Image();
            if (src.indexOf('https://') === 0 || src.indexOf('http://') === 0)
                image.crossOrigin = '*';

            image.src = src;
            image.onload = function () {
                resolve(image);
            }
            image.onerror = function () {
                reject(new Error('图片加载失败'));
            }
        })
    }


</script>
</body>
</html>